/* $Id: hash.c 3553 2011-05-05 06:14:19Z nanang $ */
/* 
 * Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
 * Copyright (C) 2003-2008 Benny Prijono <benny@prijono.org>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA 
 */
#include <dpl/hash.h>
#include <dpl/log.h>
//#include <dpl/string.h>
//#include <dpl/pool.h>
#include <dpl/os.h>
//#include <dpl/ctype.h>
#include <dpl/dpl_assert.h>


D_LOG_DOMAIN(hash,"this is a case, how to use");
/**
 * The hash multiplier used to calculate hash value.
 */
#define DPL_HASH_MULTIPLIER	33


struct dpl_hash_entry
{
    struct dpl_hash_entry *next;
    void *key;
    dpl_uint32_t hash;
    dpl_uint32_t keylen;
    void *value;
};


struct dpl_hash_table_t
{
    dpl_hash_entry     **table;
    unsigned		count, rows;
    dpl_hash_iterator_t	iterator;
};



dpl_uint32_t dpl_hash_calc(dpl_uint32_t hash, const void *key, 
				 unsigned keylen)
{
    DPL_CHECK_STACK();

    if (keylen==DPL_HASH_KEY_STRING) {
	const dpl_uint8_t *p = (const dpl_uint8_t*)key;
	for ( ; *p; ++p ) {
	    hash = (hash * DPL_HASH_MULTIPLIER) + *p;
	}
    } else {
	const dpl_uint8_t *p = (const dpl_uint8_t*)key,
			      *end = p + keylen;
	for ( ; p!=end; ++p) {
	    hash = (hash * DPL_HASH_MULTIPLIER) + *p;
	}
    }
    return hash;
}

dpl_uint32_t dpl_hash_calc_tolower( dpl_uint32_t hval,
                                          char *result,
                                          const dpl_str_t *key)
{
    long i;

#if defined(DPL_HASH_USE_OWN_TOLOWER) && DPL_HASH_USE_OWN_TOLOWER != 0
    for (i=0; i<key->slen; ++i) {
	dpl_uint8_t c = key->ptr[i];
	if (c & 64)
	    result[i] = (char)(c | 32);
	else
	    result[i] = (char)c;
	hval = hval * DPL_HASH_MULTIPLIER + result[i];
    }
#else
    for (i=0; i<key->slen; ++i) {
	result[i] = (char)tolower(key->ptr[i]);
	hval = hval * DPL_HASH_MULTIPLIER + result[i];
    }
#endif

    return hval;
}


dpl_hash_table_t* dpl_hash_create(dpl_pool_t *pool, unsigned size)
{
    dpl_hash_table_t *h;
    unsigned table_size;
    
    /* Check that DPL_HASH_ENTRY_BUF_SIZE is correct. */
    dpl_assert(sizeof(dpl_hash_entry)<=DPL_HASH_ENTRY_BUF_SIZE);

    h = malloc(sizeof( dpl_hash_table_t));
    h->count = 0;

    dpl_v ("hashtbl", "hash table %p created from pool ", h);

    /* size must be 2^n - 1.
       round-up the size to this rule, except when size is 2^n, then size
       will be round-down to 2^n-1.
     */
    table_size = 8;
    do {
	table_size <<= 1;    
    } while (table_size < size);
    table_size -= 1;
    
    h->rows = table_size;
    h->table = (dpl_hash_entry**)
    	       calloc( table_size+1, sizeof(dpl_hash_entry*));
    return h;
}

static dpl_hash_entry **find_entry( dpl_pool_t *pool, dpl_hash_table_t *ht, 
				   const void *key, unsigned keylen,
				   void *val, dpl_uint32_t *hval,
				   void *entry_buf)
{
    dpl_uint32_t hash;
    dpl_hash_entry **p_entry, *entry;

    if (hval && *hval != 0) {
	hash = *hval;
	if (keylen==DPL_HASH_KEY_STRING) {
	    keylen = strlen((const char*)key);
	}
    } else {
	/* This slightly differs with dpl_hash_calc() because we need 
	 * to get the keylen when keylen is DPL_HASH_KEY_STRING.
	 */
	hash=0;
	if (keylen==DPL_HASH_KEY_STRING) {
	    const dpl_uint8_t *p = (const dpl_uint8_t*)key;
	    for ( ; *p; ++p ) {
		hash = hash * DPL_HASH_MULTIPLIER + *p;
	    }
	    keylen = p - (const unsigned char*)key;
	} else {
	    const dpl_uint8_t *p = (const dpl_uint8_t*)key,
				  *end = p + keylen;
	    for ( ; p!=end; ++p) {
		hash = hash * DPL_HASH_MULTIPLIER + *p;
	    }
	}

	/* Report back the computed hash. */
	if (hval)
	    *hval = hash;
    }

    /* scan the linked list */
    for (p_entry = &ht->table[hash & ht->rows], entry=*p_entry; 
	 entry; 
	 p_entry = &entry->next, entry = *p_entry)
    {
	if (entry->hash==hash && entry->keylen==keylen &&
	    memcmp(entry->key, key, keylen)==0) 
	{
	    break;	
	}
    }

    if (entry || val==NULL)
	return p_entry;

    /* Entry not found, create a new one. 
     * If entry_buf is specified, use it. Otherwise allocate from pool.
     */
    if (entry_buf) {
	entry = (dpl_hash_entry*)entry_buf;
    } else {
	/* Pool must be specified! */
	//dpl_assert(pool != NULL);

	entry = malloc( sizeof(dpl_hash_entry));
	dpl_v ("hashtbl", 
		   "%p: New p_entry %p created, pool used= , cap= ", 
		   ht, entry);
    }
    entry->next = NULL;
    entry->hash = hash;
    if (pool) {
	entry->key = malloc( keylen);
	memcpy(entry->key, key, keylen);
    } else {
	entry->key = (void*)key;
    }
    entry->keylen = keylen;
    entry->value = val;
    *p_entry = entry;
    
    ++ht->count;
    
    return p_entry;
}

void * dpl_hash_get( dpl_hash_table_t *ht,
			    const void *key, unsigned keylen,
			    dpl_uint32_t *hval)
{
    dpl_hash_entry *entry;
    entry = *find_entry( NULL, ht, key, keylen, NULL, hval, NULL);
    return entry ? entry->value : NULL;
}

void dpl_hash_set( dpl_pool_t *pool, dpl_hash_table_t *ht,
			  const void *key, unsigned keylen, dpl_uint32_t hval,
			  void *value )
{
    dpl_hash_entry **p_entry;

    p_entry = find_entry( pool, ht, key, keylen, value, &hval, NULL);
    if (*p_entry) {
	if (value == NULL) {
	    /* delete entry */
	    dpl_v("hashtbl", "%p: p_entry %p deleted", ht, *p_entry);
	    *p_entry = (*p_entry)->next;
	    --ht->count;
	    
	} else {
	    /* overwrite */
	    (*p_entry)->value = value;
	    dpl_v ("hashtbl", "%p: p_entry %p value set to %p", ht, 
		       *p_entry, value);
	}
    }
}

void dpl_hash_set_np( dpl_hash_table_t *ht,
			     const void *key, unsigned keylen, 
			     dpl_uint32_t hval, dpl_hash_entry_buf entry_buf, 
			     void *value)
{
    dpl_hash_entry **p_entry;

    p_entry = find_entry( NULL, ht, key, keylen, value, &hval, 
			 (void*)entry_buf );
    if (*p_entry) {
	if (value == NULL) {
	    /* delete entry */
	    dpl_v("hashtbl", "%p: p_entry %p deleted", ht, *p_entry);
	    *p_entry = (*p_entry)->next;
	    --ht->count;
	    
	} else {
	    /* overwrite */
	    (*p_entry)->value = value;
	    dpl_v("hashtbl", "%p: p_entry %p value set to %p", ht, 
		       *p_entry, value);
	}
    }
}

unsigned dpl_hash_count( dpl_hash_table_t *ht )
{
    return ht->count;
}

dpl_hash_iterator_t* dpl_hash_first( dpl_hash_table_t *ht,
					   dpl_hash_iterator_t *it )
{
    it->index = 0;
    it->entry = NULL;

    for (; it->index <= ht->rows; ++it->index) {
	it->entry = ht->table[it->index];
	if (it->entry) {
	    break;
	}
    }

    return it->entry ? it : NULL;
}

dpl_hash_iterator_t* dpl_hash_next( dpl_hash_table_t *ht, 
					  dpl_hash_iterator_t *it )
{
    it->entry = it->entry->next;
    if (it->entry) {
	return it;
    }

    for (++it->index; it->index <= ht->rows; ++it->index) {
	it->entry = ht->table[it->index];
	if (it->entry) {
	    break;
	}
    }

    return it->entry ? it : NULL;
}

void* dpl_hash_this( dpl_hash_table_t *ht, dpl_hash_iterator_t *it )
{
    DPL_CHECK_STACK();
    DPL_UNUSED_ARG(ht);
    return it->entry->value;
}

#if 0
void dpl_hash_dump_collision( dpl_hash_table_t *ht )
{
    unsigned min=0xFFFFFFFF, max=0;
    unsigned i;
    char line[120];
    int len, totlen = 0;

    for (i=0; i<=ht->rows; ++i) {
	unsigned count = 0;    
	dpl_hash_entry *entry = ht->table[i];
	while (entry) {
	    ++count;
	    entry = entry->next;
	}
	if (count < min)
	    min = count;
	if (count > max)
	    max = count;
	len = dpl_snprintf( line+totlen, sizeof(line)-totlen, "%3d:%3d ", i, count);
	if (len < 1)
	    break;
	totlen += len;

	if ((i+1) % 10 == 0) {
	    line[totlen] = '\0';
	    DPL_LOG(4,(__FILE__, line));
	}
    }

    DPL_LOG(4,(__FILE__,"Count: %d, min: %d, max: %d\n", ht->count, min, max));
}
#endif

